package com.tiantian.system.job;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.aizuda.snailjob.client.model.ExecuteResult;
import com.tiantian.common.core.domain.ResponseResult;
import lombok.Data;


/**
 * 任务操作工具类
 *
 * @author tiantian
 */
public class JobHelper {

    private static final String changeTaskStatusURL = "http://10.226.8.14:8080/snail-job/job/status";
    private static final String loginURL = "http://10.226.8.14:8080/snail-job/auth/login";
    private static final String nameSpaceId = "2230f5e1a28c4c13b1aa8d83796b83ed";

    /**
     * 关闭任务
     */
    public static boolean closeTask(int taskId) {
        return changeTaskStatus(taskId, 0);
    }

    /**
     * 打开任务
     */
    public static boolean openTask(int taskId) {
        return changeTaskStatus(taskId, 1);
    }

    private static boolean changeTaskStatus(int id, int jobStatus) {
        String bodyTemplate = """
                {"id": {},"jobStatus": {}}
                """;
        String result = HttpRequest.put(changeTaskStatusURL)
                .body(StrUtil.format(bodyTemplate, id, jobStatus))
                .header("Snail-Job-Auth", getToken())
                .header("Snail-Job-Namespace-Id",nameSpaceId)
                .execute().body();
        return JSONUtil.toBean(result, ExecuteResult.class).getStatus() == 1;
    }

    private static String getToken() {
        String bodyTemplate = """
                {"username": "{}","password": "{}"}
                """;
        String requestBody = StrUtil.format(bodyTemplate, "admin", SecureUtil.md5("admin"));
        String body = HttpRequest.post(loginURL).body(requestBody).execute().body();
        // 获取出token
        ResponseResult responseResult = JSONUtil.toBean(body, ResponseResult.class);
        Object result = responseResult.getData();
        loginResult loginResult = JSONUtil.toBean(result.toString(), loginResult.class);
        return loginResult.getToken();
    }

    @Data
    public static class loginResult {
        String token;
    }

}
